<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

class Dragonfly_Identity_Login
{

	public static function member()
	{
		if (empty($_POST['ulogin'])/* || !static::checkSecCode(2)*/) {
			URL::redirect(URL::index('Your_Account&error=2'), true);
		}

		$provider = \Poodle\Auth\Provider::getById(1);
		if ($provider instanceof \Poodle\Auth\Provider)
		{
			$result = Dragonfly::getKernel()->IDENTITY->authenticate(
				array(
					'auth_claimed_id' => $_POST['ulogin'],
					'auth_password'   => $_POST['user_password'],
				),
				$provider);

			self::processAuthProviderResult($result, $provider);
		}
	}

	protected static function processAuthProviderResult($result, $provider)
	{
		$K = Dragonfly::getKernel();
		if ($result instanceof \Poodle\Auth\Result\Success) {
			$ID = $K->IDENTITY;

			// Autocreate identity
			if (!$ID->id && $result->claimed_id) {
				$ID->save();
				$ID->updateAuth($this->id, $result->claimed_id);
			}

			if (!$ID->id) {
				URL::redirect(URL::index('Your_Account&error=2'), true);
			}
/*
			if ($setinfo['user_level'] == 0) { URL::redirect(URL::index('Your_Account&profile='.$setinfo['user_id'])); }
			else if ($setinfo['user_level'] == -1) { URL::redirect(URL::index('Your_Account&profile='.$setinfo['user_id'])); }
*/
			$ID->updateLastVisit();

			$SQL = Dragonfly::getKernel()->SQL;
			$SQL->query("DELETE FROM {$SQL->TBL->session} WHERE host_addr=".$SQL->quoteBinary(Dragonfly_Net::ipn())." AND guest=1");
			unset($GLOBALS['CPG_SESS']['session_start']);
			if (!empty($ID->theme) && $K->CFG->member->allowusertheme) {
				$GLOBALS['CPG_SESS']['theme'] = $ID->theme;
			}

//			if (!empty($_GET['auth_cookie']) || !empty($_POST['auth_cookie'])) {
				$class = isset($K->CFG->auth_cookie->class) ? $K->CFG->auth_cookie->class : 'Dragonfly_Identity_Cookie';
				$class::set();
//			}
/*
			if (isset($_POST['redirect_uri'])) {
				$uri = $_POST['redirect_uri'];
			} else {
				$uri = ADMIN_PAGES ? \Poodle\URI::admin('/') : \Poodle\URI::index('/');
			}
			if (XMLHTTPRequest) {
				\Poodle\HTTP\Status::set(202);
			} else {
				\Poodle\URI::redirect($uri);
			}
*/
		}
/*
		else if ($result instanceof \Poodle\Auth\Result\Redirect) {
			if (!XMLHTTPRequest) {
				\Poodle\URI::redirect($result->uri);
			}
			\Poodle\HTTP\Status::set(202);
			header('Content-Type: application/json');
			echo json_encode(array(
				'status' => '302',
				'location' => $result->uri
			));
		}
		else if ($result instanceof \Poodle\Auth\Result\Form) {
			if (XMLHTTPRequest) {
				\Poodle\HTTP\Status::set(202);
				header('Content-Type: application/json');
				echo json_encode(array(
					'form' => array(
						'action' => $result->action,
						'submit' => $result->submit,
						'fields' => $result->fields
					),
					'provider_id' => $provider->id
				));
			} else {
				$K->OUT->tpl_layout = 'simple';
				$K->OUT->start();
//				$html = '<html><head><title>Redirect to OpenID Provider</title></head><body>';
				$K->OUT->body = $this->result2html($result);
//				$html.= '</body></html>';
			}
		}
		else if ($result instanceof \Poodle\Auth\Result\Error) {

			\Poodle\LOG::error(\Poodle\LOG::LOGIN, get_class($provider).'#'.$provider->code.': '.$provider->message);

			return $this->viewForm('The provided information is unknown or incorrect. Please try again');

			if (XMLHTTPRequest) {
				\Poodle\HTTP\Status::set(412);
				header('Content-Type: application/json');
				echo json_encode(array('error'=>array(
					'code'=>$result->getCode(),
					'message'=>$result->getMessage()
				)));
			} else {
				echo $result->getCode().': '.$result->getMessage();
//				print_r(get_class($result));
//				print_r($_POST['auth'][$provider->id]);
			}
		}
*/
		else
		{
			URL::redirect(URL::index('Your_Account&error=2'), true);
		}
	}

	public static function admin()
	{
		if (!empty($_POST['alogin']) && !empty($_POST['pwd']) && static::checkSecCode(1))
		{
			if ($_SESSION['DF_VISITOR']->admin->authenticate($_POST['alogin'], $_POST['pwd'])) {
				if (isset($_POST['persistent'])) {
					Dragonfly_Admin_Cookie::set();
				}
				unset($GLOBALS['CPG_SESS']['admin']);
			}
		}
	}

	protected static function checkSecCode($mode)
	{
		if ($GLOBALS['sec_code'] & $mode) {
			return (!empty($_POST['gfx_check'])
			 && !empty($_POST['gfxid'])
			 && $_POST['gfx_check'] == $_SESSION['CPG_SESS']['gfx'][$_POST['gfxid']]);
		}
		return true;
	}

}
